In today’s practical we will learn to navigate our way around R Studio and we’ll learn about where to write our R code and how to run it.

By the end of the practical you will be able to:

  1. Use the console to run code

  2. Use code chunks to write R code inside .Rmd files

  3. Run R code inside .Rmd files

Before we get started you should open the project that you created for this week, or create a new project for this practical.

Using the console

The Console pane is where you can write code that will run instantly as soon as we hit Enter↩︎.

The Console is really useful is we just want to run little bits of code, or if we want to test out a command. We’ve already used it way back in Tutorial 1/Practical 1 and 2 to run the command to install the packages we need for this course.

Understanding the console pane

When the console pane is ready to accept a command it will show a Command prompt. The command prompt just looks like a >

Take a look at the image below to see the command prompt

The console pane with the command prompt

The Console is only ready to accept commands when you can see the cursor next to the Command prompt.

If you can’t see the cursor next to the command prompt then either the previous command is still running, or the last command you typed is incomplete. We’ll take a look at both of these situations so that you can learn to recognise them.

First, we’ll see what the console looks like when it’s busy. To do this we’ll run a command that takes a while to finish. Copy the code below and paste it into the Console and hit Enter↩︎.

Sys.sleep(15)

Look at the Console pane while the command is running. Do you notice anything?

That’s right, a little red stop sign ⛔ appeared in the top right corner of the Console pane.

Notice how it goes away after 15 seconds and you get your command prompt back. You shouldn’t type in new commands while commands are already running. Just be patient and wait for it to finish.

Next, we’ll take a look at what happens with incomplete commands.

Paste the code below into the Console pane and hit Enter↩︎.

max(c(1,1),

Did you see what happened after you hit Enter↩︎?

The command prompt changed from a > to a +.

When this happens it means that the command is incomplete. If you know how to finish the command then you could just finish it. But usually incomplete commands happen when you’ve made a mistake. If you’ve made a mistake and you just want to get back to the command prompt then you can just hit the esc key.

Try hitting esc now. See how the > comes back!

Running code in the Console

We’ve just been running code in the console, but it’s worth re-emphasising a feature of the console.

Any code that is typed into the console runs as soon as you hit Enter↩︎.

You should try running some code in the Console. We can run some code that you’ve been running in the tutorial.

33 # a number
  
-5307.2455 # another number 

17 * 5 + 100 # some maths 

Notice that when you run these commands at the console you can immediately see the output produced at the console

> 3 # a number
 [1] 3
>
>

Next, we can try creating an object. We’ll just create a vector/list of 10 numbers. You can do this by running the code below in the console.

vect <- c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)

When you assign something (e.g., a list of numbers) to an object you don’t see the output. The output can either be printed at the console or a assigned to an object.

You can think of the object vect being like a box or container. When you put the list of numbers inside the box then you won’t see the list of numbers printed out.

What if we want to check what is in our object called vect? Try to figure it out, but if you can’t then click on the hint to get one.

Typing the name of the variable into the console will print the content of the object. It’s like looking inside the box.

Run the code below at the console

vect

The Environment pane

We can use the Environment pane to see any objects that we’ve created. We’ll explore this now.

But first let’s clear our Environment of any objects we’ve already created. Run the command below at the console.

rm(list = ls())

Once you’ve run this command check out the Environment pane. It should now be nice and empty.

An empty environment pane

Now try running a couple of commands. One where it print something out to the console, and one where you assign the output to an object. Take a look at the two commands below t get some ideas for commands to run.

7 + 4 / 3

my_name <- "Inigo Montoya"

Notice that when the output is printed to console you don’t get anything new appearing in your Environment pane. But when you assign something to an object then you’ll been able to see the name of the object in the Environment pane.

Writing code in R Markdown (.Rmd) files

In this course, then main place we’ll be writing R code is not in the console but inside .Rmd files.

Let’s go ahead and create a new .Rmd file. See if you can remember how to do it from last time. Click the hint if you get stuck.

You can create a new .Rmd file through the menu.

File > New File > R Markdown…

And then just click   OK  

You can just leave all the options at their default values.

Once you have a new .Rmd file clear it out so that you only have the YAML header lines and the next few lines below. It should look like the example below.

---
title: "Untitled"
output: html_document
---

```{r setup, include=FALSE}
kntir::opts_chunk$set(echo = TRUE)
```

You can go ahead and add a title and an author if you want, and then save the file into the r_docs sub-folder of your project folder.

In a previous practical you got a chance to write markdown. You made heading and wrote text and made lists.

But you can also write R code into .Rmd files. To do this, we’ll use something called a code chunk. Your document already has one code chunk. It’s called the setup chunk. We’ll cover code chunks in general first, and then swing back to the setup chunk.

Code chunks

Code chunks are marked off in your .Rmd file with fences. In their basic form they just look like this:

```{r}


```
They have an opening fence:
```{r}

And a closing fence:

```

To insert a code chunk you can just type it directly into the .Rmd file.

Just hit ` ` ` { r } enter enter ` ` `

If you can’t find the ` key then it should either be on the top row next to the 1 (on most windows keyboards with a UK layout and US layout Mac keyboards) or on the bottom row next to the z (on some UK layout Mac keyboards).

Or you can use the shortcut key of ctrl + alt + i (Windows) or ⌘ cmd + ⌥ opt + i (MacOS)

Let’s go ahread and add a code chunk! Just and the opening and closing fences. You don’t need to anything in between them for now.

So what are code chunks?

Anything inside the code chunk is treated as R code. You can write code in them but (unlike in the console) that code won’t run when you hit enter. To run the code you have to explicitly run it.

How do you explicitly run the code? There are three ways:

  1. You can put the cursor on the line you want to run and hit ctrl + enter (Windows) or ⌘ cmd + enter (MacOS)

  2. You can click on the little green triangle at the top of the code chunk to run all the code in that chunk

  3. Or finally, you can knit the document to run all the code chunks in the entire document from the top to the bottom. Note that when you knit a document with with code chunks that have errors then it will usually fail to knit. However, when you’re working on .Rmd files in these practicals they’ll usually be set up to ignore errors and just print out error messages instead.

Before we can run a code chunk we need to add some code to them.

Let’s add some code into the chunk. Add the following code

Sys.sleep(15)

Your code chunk should now look like this:

```{r}

Sys.sleep(15)

```

Once you’ve added some code, run it by either using ctrl + enter (Windows) or command + enter (MacOS) or hitting the

When you do this, you’ll see the turn into a 🕒 and then a 🟥. When it’s shows a 🟥 it means the code is running. Wait for the to return before continuing.

Now let’s clear out the code chunk again put some other code it in.

Let’s replace the:
Sys.sleep(15)

with

cat("hello world")

Now run this code chunk… What happens?

The words “hello world” get printed out below the code chunk!

So code chunks can print out output just like when you run code at the console.

Let’s now create another code chunk. Let’s include some code but this time we’ll assign the output to a variable.

Something like this:
```{r}

vect2 <- c(1,2,3,4)

```

Once you’ve inserted the code chunk, try running the code.

What do you see?

That’s right, just like when you run code at the console assigning the output to object means the output won’t be printed (shown). To show the output we can just add a new line with just the object’s name to show the content of that object.

Tip Sometimes your .Rmd file might look strange, because the syntax highlight disappears or little disappears. This happens when you don’t have matching fences or if you’ve put a code chunk inside another code chunk.

If this happens then check over your document and make sure that all your opening fences ```{r} have matching closing fences ``` and that you don’t open another fence before closing the previous one.

The environment and knitting

We’ve seen that when we create objects by either typing lines into the console or explicitly running lines we’ve written into .Rmd files then we can see the objects in the Environment pane.

The Environment pane is just going to keep track of any of the objects we create in a session and they’ll be available for the entirety of the session.

However, when you knit a .Rmd file something special happens! When you knit a document all the code in the .Rmd file is run inside a new empty enviroment. That means that when you knit the document, R will only have access to objects created inside the document. It won’t have access to objects that haven’t been created inside the document.

The best way to see what this means is to try a little test.

Go to your .Rmd file and empty it completely so that it is totally blank. Once you’ve done this, copy the following code into your document.

---
title: "Knit enviroment"
output: html_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE, error = TRUE)
```


```{r}
cat("my name is",name)
```

You’ll notice that the highlighted line makes use on a object called name

Let’s create a object called name by typing something like the following into the console.

name <- "Spartacus"

You’ll now be able to see that you have an object called name in your Environment pane.

Now let’s go to the .Rmd file. Go to the code chunk with the line cat("my name is ",name) and click the

What happens?

That’s right. It prints out my name is Spartacus

Now, try and knit the .Rmd file by using the shortcut key ctrl + shift + k (Windows) or ⌘ cmd + shift + k (MacOS) or by clicking the knit icon.

What do you see in the output document? Do you see anything strange or any errors?

You should see a line that looks something like this: ## Error in cat("my name is", name): object name not found

Why has this happened?

This has happened because the object name was not created anywhere inside that .Rmd file. We created it at the console. When you knit the document it gets knitted inside its own environment that only contains the objects created in that .Rmd file.

Do you know how to fix it?

You can fix it by creating the name object inside the .Rmd file. Try editing the code in that code chunk so that it now reads like the following.

name <- "Spartacus"
cat("my name is",name)

The setup chunk

You’d have noticed that right at the top of you document there is already a code chunk. This chunk is called the setup chunk, and it has some extra stuff in the opening fence. It’s highlighted below.

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE)
```

For now, you don’t need to worry about this extra stuff. You’ll learn more about what this means next year.

What makes the setup chunk special is that any code inside the setup chunk is automatically run before any of the other code is run. This is the case whether we knit the document or just explicitly run any of the other code chunks.

We haven’t covered packages yet, but we’ll usually be using the setup code chunk to load any packages.

Writing code in R script (.R) files

In this course, we won’t really be using .R script files at all. But we can play around with one now if you’d like to see what they’re all about.

Writing R code into the Console window is fine for one off commands or for testing things. In fact, it’s very useful for this and you should make use of it for this.

However, there’s often times where we want to write down a bunch of commands first and then run them later. There are two places we can do this. The first is in .R script files.

Let’s go ahead and create a new script file. You can do this through the menu by going to File > New File > R Script or you can use the keyboard shortcuts. Try using ctrl + shift + n (Windows) or ⌘ cmd + shift + n (MacOS).

.R script files allows you to write code but this code doesn’t run until you explicitly tell R to run it.

Let’s take some code and first we’ll paste it into the Console window.

this_class <- 'Psychology as a Science'
cat(this_class,'is great')

When you hit enter you should see something like this…

## Psychology as a Science is great

After you’ve pasted the code into the Console it runs as soon as you hit enter.

Now let’s take that exact same code and paste it into the new .R file we’ve created.

After you hit enter nothing happens?!

To make it run you have to explicitly tell R to run it. To do this you put your cursor on the line that you want to run and you hit ctrl + enter (Windows) or ⌘ cmd + enter (MacOS).

Watch the Console as you run each line and you’ll see that it runs. Code written in a .R file is just there doing nothing until you run it. If you make changes then you have to re-run it if you want to see the result of those changes.

Test your understanding